#!/usr/bin/python3
# -*- coding: utf-8 -*-

from configparser import ConfigParser
from os import path

import modules.api.deepl.deepl_translate.api as deepl
from modules.api.base_translation import BaseTranslation
from modules.utils import MY_ERROR_CODES, check_langs, get_file_encoding, print_err, print_warn

# 所有支持的语种字典
_DEEPL_COMMON_LANGS = ['ZH', 'EN', 'JA', 'DE', 'FR', 'ES', 'PT', 'IT', 'NL', 'PL', 'RU']

# 源语种字典
_DEEPL_FROM_LANGS = {
    '1': {'n': '中文', 'c': 'ZH'},
    '2': {'n': '英语', 'c': 'EN'},
    '3': {'n': '日语', 'c': 'JA'},
    '4': {'n': '德语', 'c': 'DE'},
    '5': {'n': '法语', 'c': 'FR'},
    '6': {'n': '西班牙语', 'c': 'ES'},
    '7': {'n': '葡萄牙语', 'c': 'PT'},
    '8': {'n': '意大利语', 'c': 'IT'},
    '9': {'n': '荷兰语', 'c': 'NL'},
    '10': {'n': '波兰语', 'c': 'PL'},
    '11': {'n': '俄语', 'c': 'RU'},
}

# 常用目标语种字典
_DEEPL_TO_LANGS = {
    '1': {'n': '中文', 'c': 'ZH'},
    '2': {'n': '英语', 'c': 'EN'},
    '3': {'n': '日语', 'c': 'JA'},
}


class DeepLTranslation(BaseTranslation):

    def __init__(self, section: str):

        BaseTranslation.__init__(self, section)
        self.section = section
        self._get_config()

    def translate(self, source_txt: str, to_lang: str, from_lang='EN') -> str:
        '''
        开始翻译

        - source_txt: 输入文本
        - to_lang: 目标语种
        - from_lang: 源语种
        '''

        # 由于DeepL源语言无法使用auto，故在此检测语言语种
        from_lang = check_langs(source_txt).upper()

        # 当源语言不在受支持的语种范围内时，强制将源语言设置为EN，确保翻译能正常进行
        if not from_lang in _DEEPL_COMMON_LANGS:
            from_lang = 'EN'
            print_warn('检测的源语言不在受支持的语种范围内，已强制重置为“英语”！')

        # 当源语言不在受支持的语种范围内时，强制将源语言设置为ZH，确保翻译能正常进行
        if not to_lang in _DEEPL_COMMON_LANGS:
            to_lang = 'ZH'
            print_warn('目标语言不在受支持的语种范围内，已强制重置为“中文”！')

        if to_lang == from_lang:
            print_warn('目标语种和源语种相同。')
            return source_txt

        # 原文本长度超过上限
        if len(source_txt) > self._max_char:
            print_err(MY_ERROR_CODES['ERR_10002'])
            return 'ERR_10002'

        target = ''
        try:
            target = deepl.translate(
                source_language=from_lang, target_language=to_lang, text=source_txt
            )

        except Exception as e:
            print_err(f'翻译出现异常：{e.args[0]}！')
            target = 'ERR_10001'

        return target

    def _get_config(self):
        '''
        获取配置
        '''

        config_path = path.join(
            path.abspath('.'), 'modules', 'api', 'deepl', 'config.ini'
        )
        if not path.isfile(config_path):
            return

        conf = ConfigParser()  # 调用读取配置模块中的类
        conf.optionxform = lambda option: option
        conf.read(config_path, encoding=get_file_encoding(config_path))

        self._rate = conf.getint(self.section, 'rate')
        if self._rate < 1:
            self._rate = 1
        self._max_char = conf.getint(self.section, 'max_char')
        if self._max_char < 50:
            self._max_char = 2000

    def get_from_langs(self) -> dict:
        '''
        获取源语种字典
        '''
        return _DEEPL_FROM_LANGS

    def get_to_langs(self) -> dict:
        '''
        获取目标语种字典
        '''
        return _DEEPL_TO_LANGS
